google.load('search', '1');

function doImageSearches(search1, search2) {
  var imageSearch1 = new google.search.ImageSearch();
  imageSearch1.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
                              google.search.ImageSearch.IMAGESIZE_MEDIUM);
  var imageSearch2 = new google.search.ImageSearch();
  imageSearch2.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
                              google.search.ImageSearch.IMAGESIZE_MEDIUM);
  imageSearch1.setSearchCompleteCallback(this, searchComplete2, [imageSearch1, imageSearch2]);
  imageSearch1.setResultSetSize(8);
  imageSearch2.setSearchCompleteCallback(this, searchComplete2, [imageSearch1, imageSearch2]);
  imageSearch2.setResultSetSize(8);
  imageSearch1.results = null;
  imageSearch2.results = null;
  imageSearch1.execute(search1);
  imageSearch2.execute(search2);
}

function searchComplete2(searcher1, searcher2) {
  // Check that we got results for both  
  if (searcher1.results && searcher2.results) {

    s = [];
    sindex = 0;
    
    var index1 = 0;
    var results1 = searcher1.results;
    var index2 = 0;
    var results2 = searcher2.results;
    while (index1 < results1.length || index2 < results2.length) {
      
      // pick a result to use
      var result;
      var which = (Math.random() < 0.5) ? 0 : 1;
      if (index1 >= results1.length) {
        which = 1;
      } else if (index2 >= results2.length) {
        which = 0;
      }
      if (which == 0) {
        result = results1[index1];
        index1++;
      } else {
        result = results2[index2];
        index2++;
      }

      // make an object and add it to stream
      streamObj = new Object();
      streamObj.which = which;
      var url = result.tbUrl;
      streamObj.tbUrl = url;
      streamObj.img = document.createElement('img');
      var proxiedUrl = "proxy.php?mode=native&url=" + escape(url);
//      console.log(proxiedUlr);
      streamObj.img.src = proxiedUrl;
      stream[sindex++] = streamObj;
    }
    
    // clear the results so we don't merge twice
    searcher1.results = null;
    searcher2.results = null;
    
    window.setTimeout(function(){enableStart(true)}, 1);
  }
}

function OnLoad() {
  var urlVars = getUrlVars();
  var qs = pickQuerySet();
  var search1 = qs[0];
  var search2 = qs[1];
  if (urlVars["s1"]) {
    search1 = urlVars["s1"];
  }
  if (urlVars["s2"]) {
    search2 = urlVars["s2"];
  }
  displayTerms(search1, search2);
  doImageSearches(search1, search2);
}

function getUrlVars() {
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++) {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;
}

google.setOnLoadCallback(OnLoad);
